/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 功能描述 配置使用ThreadPoolTaskExecutor 线程池
 *
 * @since 2022-03-08
 */
@Configuration
@EnableAsync
@ConditionalOnProperty(prefix = "threadpool", name = "enable", havingValue = "true")
public class SpringThreadPoolExecutorConfig {
    @Autowired
    private ThreadPoolProperty threadPoolProperty;

    /**
     * 线程池配置
     *
     * @return {@link ThreadPoolTaskExecutor}
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setKeepAliveSeconds(threadPoolProperty.getKeepAliveSeconds());
        pool.setCorePoolSize(threadPoolProperty.getCorePoolSize());
        pool.setMaxPoolSize(threadPoolProperty.getMaxPoolSize());
        pool.setQueueCapacity(threadPoolProperty.getQueueCapacity());

        // 队列满时，线程被拒绝执行策略
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        pool.setThreadNamePrefix("task-order-support-thread--");
        return pool;
    }
}